package org.carl.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @show 核心service服务类,提供解析controller及自动注入同名称属性
 * @version 0.02
 * @author carl
 *
 */
public class CoreServlet extends CarlServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		super.service(request, response);
		// 获取执行链接
		String uri = request.getRequestURI();
		// 当前核心类的包
		Package pack = this.getClass().getPackage();
		// 存放controller的文件夹
		String pac = pack.getName().substring(0, pack.getName().lastIndexOf(".") + 1) + "controller";
		String path[] = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf(".")).split("_");
		Objects.requireNonNull(path, "文件路径有误,请检查..");
		// 获取参数
		Map<String, String[]> parameters = getParameters(request);
		String controller = path[0].substring(0, 1).toUpperCase() + path[0].substring(1, path[0].length());
		String method = path[1];
		//错误消息
		String msg=null;
		try {
			Class<?> clazz = Class.forName(pac + "." + controller);
			Method m = null;
			try {
				// 寻找类中无参数方法
				m = clazz.getMethod(method, new Class[] {});
			} catch (NoSuchMethodException e) {
				try {
					// 寻找类中两个参数方法
					m = clazz.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
				} catch (NoSuchMethodException e1) {
					msg=clazz.getName()+"类中对应"+method+"方法有误,请检查...";
					throw new RuntimeException(msg);
					
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			}
			Objects.requireNonNull(m,msg);
			Object instance = clazz.newInstance();
			// 初始化参数等
			super.initialFields(instance,parameters);
			super.executeTarget(request, response, instance, m);
		} catch (ClassNotFoundException e) {
			msg = String.format("%s包下%s类不存在", pac, controller);
			// 需要报错404
			response.sendError(404, msg);
		} catch (Exception e) {
			response.sendError(500, e.getMessage());
		}
	}

	/**
	 * 获取所有的参数
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return Map<String, String[]>
	 */
	private Map<String, String[]> getParameters(HttpServletRequest request) {
		Map<String, String[]> parameters = new HashMap<String, String[]>();
		parameters.putAll(request.getParameterMap());
		return parameters;
	}
}
